﻿namespace Mp3Observer.Common.Behaviors
{
    #region usings

    using System.Windows;
    using System.Windows.Interactivity;

    #endregion

    /// <summary>
    /// This behavior can be used to set the focus on a specific UIElement by chaning the IsFocused value.
    /// </summary>
    /// <example>
    /// <code>
    /// <![CDATA[ 
    ///    <ListBox>
    ///         <i:Interaction.Behaviors>
    ///             <behaviors:FocusBehavior IsFocused="{Binding IsFocused}" />
    ///          </i:Interaction.Behaviors>
    /// ]]>
    /// </code>
    /// </example>
    public class FocusBehavior : Behavior<UIElement>
    {
        /// <summary>
        /// DependencyProperty for IsFocused needed for databinding to get notified from PropertyChangedCallback.
        /// </summary>
        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.Register("IsFocused", typeof(bool), typeof(FocusBehavior),
            new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIsFocusedPropertyChanged)));

        /// <summary>
        /// Gets or sets a value indicating whether this instance is focused.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is focused; otherwise, <c>false</c>.
        /// </value>
        public bool IsFocused
        {
            get { return (bool)GetValue(IsFocusedProperty); }
            set { SetValue(IsFocusedProperty, value); }
        }

        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        /// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks>
        protected override void OnAttached()
        {
            base.OnAttached();
        }

        /// <summary>
        /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        /// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        /// <summary>
        /// Called when [is focused property changed].
        /// </summary>
        /// <param name="dependencyObject">The dependency object.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnIsFocusedPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var source = (FocusBehavior)dependencyObject;
            VisualHelper.Focus((UIElement)source.AssociatedObject);
        }
    }
}
